package com.ryan.security.core.authentication.mobile;

import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Created by kaimin on 3/1/2019.
 * time : 00:35
 */
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService myUserDetailService;

    //进行身份认证的逻辑
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken auth = (SmsCodeAuthenticationToken) authentication;
        //根据手机号码去进行认证
        UserDetails user = myUserDetailService.loadUserByUsername((String) auth.getPrincipal());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SmsCodeAuthenticationToken result=new SmsCodeAuthenticationToken(user,user.getAuthorities());
        result.setDetails(auth.getDetails());

        return result;
    }

    //判断传输进来的是不是SmsCodeAuthenticationToken这种类型的
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
